<?php

namespace app\modules\admin\controllers;

use app\models\AgentProfit;
use app\models\Card;
use app\models\CardDatalog;
use app\models\ManagerLog;
use app\models\UserCardRecharge;
use app\models\UserCardReserveRecharge;
use app\models\Agent;
use app\models\AgentAccount;
use app\models\AgentBill;
use app\models\AgentPackage;
use app\models\Payment;
use app\models\Refund;
use app\models\MoneyChange;
use app\models\CommissionBill;
use app\models\MultiCommissionBill;
use app\models\CardUsageSub;
use app\models\MembershipKey;
use app\models\KeyMap;
use app\models\Package;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use Exception;
use Yii;
use yii\data\Pagination;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\db\Expression;
/**
 * 财务管理
 * Class FinanceController
 * @package app\modules\admin\controllers
 */
class FinanceController extends BaseController
{   
    public function actionCallpay(){
        $url = 'http://cu.mangcaoiot.com/api/card/recharge?version=1.0.0&app_id=weixin&nonce=123456';
        $app_id = 'weixin';
        $nonce = '123456';
        $timestamp = time();
        $version = '1.0.0';
        $appsecrect = 'dG5sXL9upS3IA3GkJvOetzlQbTdNwlOZ';
        $sign = md5($app_id.$nonce.$timestamp.$version.$appsecrect);
        $urls = $url."&amp;timestamp=".$timestamp."&amp;sign=".$sign;
        echo $urls;
        exit;
    }
    
    //视频会员卡密
    public function actionMembershipKey(){
        if (!$this->manager->can('finance/membership-key')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $search_key_status = $this->get('search_key_status');
        $query = MembershipKey::find();
        $query->andFilterWhere(['status'=>$search_key_status]);
        $query->andFilterWhere(['iccid'=>$this->get('search_iccid')]);
        $query->orderBy('execute_time DESC');
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->offset($pagination->offset)->limit($pagination->limit);
        $keyList = $query->all();

        return $this->render('membership_key_list', [
            'keyList' => $keyList,
            'pagination' => $pagination,
        ]);
    }
    /**
     * 用户卡充值列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionUserCardRechargeList()
    {
        if (!$this->manager->can('finance/user-card-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $search_start_time = $this->get('search_start_time');
        $search_end_time = $this->get('search_end_time');
        $start_time = strtotime($this->get('search_start_time'));
        $end_time = strtotime($this->get('search_end_time'));
        $query = UserCardRecharge::find()->alias('recharge');
        if(!empty($this->get('search_iccid'))){
            $card = Card::find()->andFilterWhere(['like','iccid',$this->get('search_iccid')])->one();
        }
        $query->andFilterWhere(['card_id'=>$card->id]);
        $query->andFilterWhere(['trade_type'=>$this->get('search_trade_type')]);
        $query->andFilterWhere(['recharge_type'=>$this->get('search_recharge_type')]);
        $query->andFilterWhere(['source'=> $this->get('search_source')]);
        $query->andFilterWhere(['recharge.id'=>$this->get('search_id')]);
        $query->andFilterWhere(['recharge.trade_no' => $this->get('search_trade_no')]);
        $query->andFilterWhere(['is_show'=>1]);
        if (!empty($this->get('search_agentname'))) {
            /** @var Agent $searchAgent */
            $searchAgent = Agent::find()
                ->andWhere(['username' => $this->get('search_agentname')])
                ->one();
            if (empty($searchAgent)) {
                throw new NotFoundHttpException('没有找到代理商【' . $this->get('search_agentname') . '】。');
            } else {
                $agentIdList = [$searchAgent->id];
                if ($this->get('search_sub_agent') == 1) { // 包含下级代理商
                    $agentIdList = array_merge($agentIdList, $searchAgent->getSubAidList());

                }
                $query->andFilterWhere(['recharge.agent_id' => $agentIdList]);
            }
        }

        if(!$search_start_time && !$search_end_time){
            $query->andFilterWhere(['recharge.create_time'=>'']);
        }else{
            if(!$search_end_time){
                $time = strtotime(date('Y-m-d',$start_time)) + 86399;
                $query->andFilterWhere(['between','recharge.create_time',$start_time,$time]);
            }else{
                $search_end_times = $end_time + 86399;
                $query->andFilterWhere(['between','recharge.create_time',$start_time,$search_end_times]);
            }
            
        }
        
        if ($this->get('export') == 'excel') { // 导出Excel文件
            try {
                $excel = new Spreadsheet();
                $sheet = $excel->setActiveSheetIndex(0);
                foreach ([
                             '编号',
                             '代理商',
                             'ICCID',
                             '套餐',
                             '时长(月)',
                             '成本价',
                             '销售价',
                             '充值状态',
                             '交易编号',
                             '支付时间',
                             '来源',
                         ] as $index => $title) {
                    $sheet->setCellValue(chr(65 + $index) . '1', $title);
                }
                $sheet->getStyle('A1:Z1')->applyFromArray(['font' => ['bold' => true], 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER]]);
                $r = 2;
                /** @var Card $card */
                foreach ($query->each() as $recharge) {
                    $sheet->setCellValueExplicitByColumnAndRow(1, $r, $recharge->id, DataType::TYPE_NUMERIC);
                    $sheet->setCellValueExplicitByColumnAndRow(2, $r, $recharge->agent->username,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(3, $r, $recharge->card->iccid,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(4, $r, $recharge->package->name,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(5, $r, $recharge->term_length,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(6,$r, $recharge->price, DataType::TYPE_NUMERIC);
                    $sheet->setCellValueExplicitByColumnAndRow(7,$r, $recharge->money,DataType::TYPE_NUMERIC);
                    $sheet->setCellValueExplicitByColumnAndRow(8, $r, KeyMap::getValue('recharge_type', $recharge->recharge_type), DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(9,$r, $recharge->trade_no,DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(10,$r, Yii::$app->formatter->asDatetime($recharge->pay_time),DataType::TYPE_STRING);
                    $sheet->setCellValueExplicitByColumnAndRow(11, $r, KeyMap::getValue('source', $recharge->source), DataType::TYPE_STRING);
                    $r++;
                }
                $sheet->freezePane('A2');

                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="卡充值订单_' . date('Y-m-d') . '.xls"');
                header('Cache-Control: max-age=0');
                $excelWriter = IOFactory::createWriter($excel, 'Xls');
                $excelWriter->save('php://output');
            } catch (\Exception $e) {
                Yii::error('导出Excel文件时出错：' . $e->getMessage());
                Yii::error($e->getTraceAsString());
                echo $e->getMessage();
            }
            die();
        }
        $query->orderBy('recharge.create_time DESC');
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->offset($pagination->offset)->limit($pagination->limit);
        $rechargeList = $query->all();

        return $this->render('user_card_recharge_list', [
            'rechargeList' => $rechargeList,
            'pagination' => $pagination,
            'search_start_time' =>  $search_start_time,
            'search_end_time' => $search_end_time,
        ]);
    }

    /**
     * 卡充值详情
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionRechargeView()
    {
        if (!$this->manager->can('finance/user-card-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $recharge = UserCardRecharge::findOne(['id' => $this->get('id')]);
        if (empty($recharge)) {
            throw new NotFoundHttpException('没有找到充值信息。');
        }
        $this->layout = false; //不使用布局
        $this->layout = "new";
        return $this->render('recharge_view', [
            'recharge' => $recharge,
        ]);
    }

    /**
     * 设置充值已支付AJAX接口
     * @return array
     * @throws BadRequestHttpException
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionSetRechargePaid()
    {
        if (!$this->manager->can('finance/user-card-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $recharge = UserCardRecharge::findOne(['id' => $this->get('id')]);
        if (empty($recharge)) {
            throw new NotFoundHttpException('没有找到充值信息。');
        }
        if ($recharge->status != UserCardRecharge::STATUS_WAIT_PAY) {
            throw new BadRequestHttpException('充值状态异常，不能设置为已支付。');
        }

        $trans = Yii::$app->db->beginTransaction();
        try {
            $recharge->setPaid();

            $trans->commit();

            ManagerLog::info($this->manager->id, '设置充值已支付', $recharge->id);

            return [];
        } catch (Exception $e) {
            try {
                $trans->rollBack();
            } catch (Exception $_) {
            }
            return ['error' => 'SERVER', 'message' => $e->getMessage()];
        }
    }

    /**
     * 增加卡时长AJAX接口
     * @return array
     * @throws BadRequestHttpException
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionAddRechargeTerm()
    {
        if (!$this->manager->can('finance/user-card-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $recharge = UserCardRecharge::findOne(['id' => $this->get('id')]);
        if (empty($recharge)) {
            throw new NotFoundHttpException('没有找到充值信息。');
        }
        if ($recharge->status != UserCardRecharge::STATUS_PAID) {
            throw new BadRequestHttpException('充值状态异常，不能增加套餐时长。');
        }

        $card = Card::findOne(['id' => $recharge->card_id]);
        if ($card->package_id != $recharge->package_id) {
            return ['error' => 'SERVER', 'message' => '充值套餐和卡套餐不匹配。'];
        }
        if ($card->term_length_unit != $recharge->term_length_unit) {
            return ['error' => 'SERVER', 'message' => '充值有效期单位和卡套餐有效期单位不匹配。'];
        }
        if ($card->status == Card::STATUS_DEACTIVATED && $card->term_end_time < time()) { // 卡已经停用且超过有效期了
            // 接口激活
            try {
                $card->setStatus(Card::STATUS_ACTIVATED);
            } catch (Exception $e) {
                Yii::warning('激活卡时接口错误：' . $e->getMessage());
                Yii::warning($e->getTraceAsString());
                return ['error' => 'SERVER', 'message' => '激活卡时接口错误：' . $e->getMessage()];
            }
            // 更新当前时间为激活时间
            $card->updateAttributes(['active_time' => time(), 'status' => Card::STATUS_ACTIVATED]);
            $card->term_length = $recharge->term_length;
            $card->calcTermEnd();
        } elseif ($card->status == Card::STATUS_ACTIVATED) { // 卡已经激活
            // 增加时长并重新计算有效期
            $card->updateCounters(['term_length' => $recharge->term_length]);
            $card->calcTermEnd();
        }
        $recharge->updateAttributes(['status' => UserCardRecharge::STATUS_RECHARGE, 'update_time' => time()]);

        return [];
    }
    /**
     * 用户卡预充值列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionUserCardReserveRechargeList()
    {
        if (!$this->manager->can('finance/user-card-reserve-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $current_time = $this->get('search_time');
        $start_time = strtotime($current_time);
        $end_time = $start_time + 86399;
        $query = UserCardReserveRecharge::find()->alias('recharge');
        $query->joinWith('user user');
        $query->joinWith('agent agent');
        $query->joinWith('card card');
        $query->andFilterWhere(['like','agent.username',$this->get('search_agentname')]);
        $query->andFilterWhere(['like','card.iccid',$this->get('search_iccid')]);
        $query->andFilterWhere(['source'=> $this->get('search_source')]);
        $query->andFilterWhere(['execute_status' => $this->get('search_status')]);
        if(!$current_time){
            $query->andFilterWhere(['recharge.active_time'=> '']);
        }else{
            $query->andFilterWhere(['between','recharge.active_time',$start_time,$end_time]);
        }
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('recharge.id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $rechargeList = $query->all();

        return $this->render('user_card_reserve_recharge_list', [
            'rechargeList' => $rechargeList,
            'pagination' => $pagination,
            'current_time' => $current_time
        ]);
    }
    
    /**
     * 卡预充值详情
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionReserveRechargeView()
    {
        if (!$this->manager->can('finance/user-card-reserve-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $recharge = UserCardReserveRecharge::findOne(['id' => $this->get('id')]);
        if (empty($recharge)) {
            throw new NotFoundHttpException('没有找到充值信息。');
        }
        $this->layout = false;
        $this->layout = "new";
        return $this->render('reserve_recharge_view', [
            'recharge' => $recharge,
        ]);
    }
    /**
     * 代理商收益列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionAgentProfit()
    {
        if (!$this->manager->can('finance/agent-profit')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $current_time = $this->get('search_time');
        $query = AgentProfit::find()->alias('profit');
        
        if(!empty($this->get('search_agent'))){
            $agent = Agent::findOne(['username'=>$this->get('search_agent')]);
        }
        $query->andFilterWhere(['profit.agent_id' => $agent->id]);
        $query->andFilterWhere(['profit.source' => $this->get('search_source')]);
        $query->andFilterWhere(['profit.is_show'=>1]);
        $query->andFilterWhere(['profit.profit_type'=>1]);
        if(!$current_time){
            $query->andFilterWhere(['profit.same_time'=> '']);
        }else{
            $query->andFilterWhere(['profit.same_time' => strtotime($this->get('search_time'))]);
        }
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('profit.id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $profitList = $query->all();

        return $this->render('agent_profit_list', [
            'profitList' => $profitList,
            'pagination' => $pagination,
            'current_time' => $current_time,
        ]);
    }
    /**
     * 代理商激活奖励列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionActiveReward(){
        if (!$this->manager->can('finance/agent-profit')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $current_time = $this->get('search_time');
        $query = AgentProfit::find()->alias('profit');
        $query->joinWith('agent agent');
        $query->joinWith('recharge recharge');
        $query->joinWith('package package');
        $query->joinWith('card card');
        $query->andFilterWhere(['agent.username' => $this->get('search_agent')]);
        $query->andFilterWhere(['profit.source' => $this->get('search_source')]);
        $query->andFilterWhere(['profit.pay_status'=>$this->get('search_pay_status')]);
        $query->andFilterWhere(['profit.profit_type'=>2]);
        $query->andFilterWhere(['profit.is_show'=>1]);
        if(!$current_time){
            $query->andFilterWhere(['profit.same_time'=> '']);
        }else{
            $query->andFilterWhere(['profit.same_time' => strtotime($this->get('search_time'))]);
        }
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('profit.create_time DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $profitList = $query->all();
        $pay_type = '2';
        return $this->render('active_reward_list', [
            'profitList' => $profitList,
            'pagination' => $pagination,
            'current_time' => $current_time,
            'pay_type'   => $pay_type
        ]);
    }
    //支付分成佣金
    public function actionSetPaymentPaid(){
        $data['id'] = $this->get('id');
        $data['agent_id'] = $this->get('agentid');
        $data['amount'] = $this->get('money');
        $data['description'] = '佣金发放';
        $data['pay_type'] = $this->get('pay_type');
        $payment_type = $this->get('payment_type');
        $start_time = $this->get('start_time');
        $end_time = $this->get('end_time');
        $agent = Agent::findOne(['id' => $this->get('agentid')]);
        $username = $agent['username'];
        $urls = "http://wx.mangcaoiot.com/index.php?g=Wap&m=IotCard&a=getWechatid"."&username=".$username;
        $result = $this->getUrl($urls);
        $arr = json_decode($result,true);
        $data['userid'] = $arr['wechat_id'];
        $data['name'] = $agent['username'];
        $url = "http://wx.mangcaoiot.com/index.php?g=Wap&m=CiotCard&a=transfers2";
        $results = $this->curl_post($url,$data);
        $pay_code = json_decode($results,true);
        
        if($pay_code['code'] == 1){
            if($payment_type == 2){
                Yii::$app->db->createCommand()->update('commission_bill', ['pay_status' => 2], 'id = :id',['id' => $this->get('id')], 'agent_id = :agent_id',['agent_id' => $this->get('agentid')], 'generate_time = :generate_time',['generate_time' => $this->get('gtime')])->execute(); 
            }elseif($payment_type == 1){
                Yii::$app->db->createCommand()->update('multi_commission_bill', ['pay_status' => 2], 'id = :id',['id' => $this->get('id')], 'agent_id = :agent_id',['agent_id' => $this->get('agentid')], 'generate_time = :generate_time',['generate_time' => $this->get('gtime')])->execute(); 

                $list = CommissionBill::find()->andFilterWhere(['agent_id'=>$this->get('agentid')])->andFilterWhere(['between','generate_time',$start_time,$end_time])->andFilterWhere(['pay_status'=>1])->all();
                foreach($list as $key=>$value){
                    Yii::$app->db->createCommand()->update('commission_bill', ['pay_status' => 2], 'id = :id',['id' => $value['id']], 'agent_id = :agent_id',['agent_id' => $value['agent_id']], 'generate_time = :generate_time',['generate_time' => $this->get('gtime')])->execute();
                }
            }
            
            return [];
        }else{
            return ['error' => 'SERVER', 'message' => $pay_code['msg']];
        }
             
    }
    //支付激活奖励
    public function actionSetActivePaymentPaid(){
        $data['id'] = $this->get('id');
        $data['agent_id'] = $this->get('agentid');
        $data['amount'] = $this->get('money');
        $data['description'] = '激活奖励';
        $data['pay_type'] = $this->get('pay_type');
        $agent = Agent::findOne(['id' => $this->get('agentid')]);
        $username = $agent['username'];
        $urls = "http://wx.mangcaoiot.com/index.php?g=Wap&m=IotCard&a=getWechatid"."&username=".$username;
        $result = $this->getUrl($urls);
        $arr = json_decode($result,true);
        $data['userid'] = $arr['wechat_id'];
        $data['name'] = $agent['username'];
        $url = "http://wx.mangcaoiot.com/index.php?g=Wap&m=CiotCard&a=transfers2";
        $results = $this->curl_post($url,$data);
        $pay_code = json_decode($results,true);
        if($pay_code['code'] == 1){
            Yii::$app->db->createCommand()->update('agent_profit', ['pay_status' => 2], 'id = :id',['id' => $this->get('id')], 'agent_id = :agent_id',['agent_id' => $this->get('agentid')], 'same_time = :same_time',['same_time' => $this->get('gtime')])->execute(); 
            return [];
        }else{
            return ['error' => 'SERVER', 'message' => $pay_code['msg']];
        }
           
    }
    //代理商付款记录
    public function actionPaymentList(){

        if (!$this->manager->can('finance/payment-list')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $current_time = $this->get('search_time');
        $query = Payment::find()->alias('pay');
        $query->andFilterWhere(['name'=>$this->get('search_agent')]);
        if(!$current_time){
            $query->andFilterWhere(['payment_time'=> '']);
        }else{
           $query->andFilterWhere(['time' => strtotime($this->get('search_time'))]); 
        } 
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('pay.id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $paymentList = $query->all();

        return $this->render('payment_list', [
            'paymentList' => $paymentList,
            'pagination' => $pagination,
            'current_time' => $current_time,
        ]);
    }
    //代理商佣金列表
    public function actionAgentCommission(){
        $query = strtotime($this->get('search_time'));
        $query = CommissionBill::find()->alias('bill');
        $query->andFilterWhere(['agentname'=> $this->get('search_username')]);
        if(!$this->get('search_time')){
            $query->andFilterWhere(['bill.generate_time'=> '']);
        }else{
           $query->andFilterWhere(['bill.generate_time' => strtotime($this->get('search_time'))]); 
        }
        $query->andFilterWhere(['pay_status'=>$this->get('search_status')]);
        $query->andFilterWhere(['bill.id'=>$this->get('search_id')]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy(['id'=>SORT_DESC]);
        $query->offset($pagination->offset)->limit($pagination->limit);

        $billList = $query->all();
        $pay_type = '2';
        $payment_type = '2'; //付款方式 批量付款1,单个付款2
        return $this->render('agent_commission_list',[
            'billList' => $billList,
            'pagination' => $pagination,
            'pay_type' => $pay_type,
            'payment_type' => $payment_type
        ]);
    }
    //代理商佣金生成账单
    public function actionGenerateAgentBill(){
        $date = strtotime($this->get('day'));
        $agent_name = $this->get('name');
        $agent = Agent::findOne(['username'=>$agent_name]);
        if(empty($agent_name)){
            $agent_id = '';
        }else{
            $agent_id = $agent->id;
        }
        $profitList = (new \yii\db\Query())
        ->select(['agent_profit.id as id','agent.id as agent_id','agent.username as username','agent_profit.comm_type as comm_type','sum(agent_profit.money) as sum_money','agent_profit.create_time as create_time','sum(agent_profit.pay_status) as sum_count'])
        ->from('agent_profit')
        ->join('join','agent','agent_profit.agent_id=agent.id')
        ->groupBy('agent_profit.agent_id')
        ->andFilterWhere(['same_time'=>$date])
        ->andFilterWhere(['is_show'=>1])
        ->andFilterWhere(['>','agent_profit.money',0])
        ->andFilterWhere(['profit_type'=>1])
        ->andFilterWhere(['agent_profit.agent_id'=>$agent_id])
        ->all();
        if(!$profitList){
            return ['error' => 'EMPTY', 'message' => '所选日期无收益记录，生成账单失败！'];
        }
        foreach($profitList as $key=>$value){
            $bill = new CommissionBill();
            $bill->agent_id = $profitList[$key]['agent_id'];
            $bill->generate_time = strtotime(date('Y-m-d',$date));
            $bill->money = $profitList[$key]['sum_money'];
            $bill->create_time = time();
            $bill->agentname = $profitList[$key]['username'];
            $bill->count = $profitList[$key]['sum_count'];
			$bill->comm_type = $profitList[$key]['comm_type'];
            $bill->save();
        }

        $result = CommissionBill::find()
            ->andWhere(['generate_time' => $date])
            ->asArray()
            ->select([
                'agent_id' => 'agent_id', 
                'bill_id'  => 'id',
                'money' => new Expression('sum(money)'),
                'amount' => 'count',
            ])
            ->groupBy('agent_id')
            ->all();
        foreach ($result as $key=>$value){
            $agentBill = new AgentBill();
            $agentBill->agent_id = $result[$key]['agent_id'];
            $agentBill->bill_id  = $result[$key]['bill_id'];
            $agentBill->day = date('Y-m-d',$date);
            $agentBill->pay_count = $result[$key]['amount'];
            $agentBill->money = $result[$key]['money'];
            $agentBill->status = 1;
            $agentBill->save();
        }
        return [];
    }
    
     //执行预充值
    public function actionSetReserveRechargeExecute(){
        $id = $this->get('id');
        //编号后加字母区分预充值执行和其它充值，防止再次出现编号重复
        $order_sn = date('YmdHis').rand(1000, 9999)."E";
        $reserve = UserCardReserveRecharge::findOne(['id'=>$id]);
        $datas['card']['iccid'] = $reserve->iccid;
        $datas['term_length'] = $reserve->term_length;
        $datas['price'] = $reserve->price;
        $datas['money'] = $reserve->money;
        $datas['trade_type'] = $reserve->trade_type;
        $datas['trade_no'] = $order_sn;
        $datas['trade_id'] = $order_sn;//交易编号
        $datas['app_id'] = "weixin";
        $datas['uid'] = $reserve->uid;
        $datas['agent_id'] = $reserve->agent_id;
        $datas['package_id'] = $reserve->package_id;
        $datas['term_length_unit'] = $reserve->term_length_unit;
        $datas['source'] = $reserve->source;
        $datas['card_recharge_id'] = $reserve->card_recharge_id;
        $data_string = json_encode($datas);
        $getMoneyUrl="http://cu.mangcaoiot.com/api/card/agent-reserve-recharge?version=1.0.0&app_id=weixin&nonce=123456&timestamp=1&sign=0123456789abcdef&token=";
        $iot_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MzU4MTM2NzYsInVpZCI6NCwiYXBwIjoid2VpeGluIn0=.6428835f2b1518367de235f6bd044eb41ae995f9b13dfe289faeb8448f6ce16f";
        $getMoneyUrl = $getMoneyUrl.$iot_token;
        $result = $this->UrlPost($getMoneyUrl,$data_string);
        $results = json_decode($result,true);
        if($results['error'] == ''){
            Yii::$app->db->createCommand()->update('user_card_reserve_recharge', ['execute_status' => 1], 'id = :id',['id' => $reserve['id']])->execute(); 
            return [];
        }else{
            return ['error' => 'SERVER','message' => '执行失败'];
        }
             
    }
    public function actionSetRechargeStatusA(){
        $id = $this->get('id');
        Yii::$app->db->createCommand()->update('user_card_recharge', ['recharge_type' => 1], 'id = :id',['id' => $id])->execute(); 
            return [];

    }
    public function actionSetRechargeStatusB(){
        $id = $this->get('id');
        Yii::$app->db->createCommand()->update('user_card_recharge', ['recharge_type' => 2], 'id = :id',['id' => $id])->execute(); 
            return [];

    }
    public function actionSetRechargeStatusC(){
        $id = $this->get('id');
        Yii::$app->db->createCommand()->update('user_card_recharge', ['recharge_type' => 3], 'id = :id',['id' => $id])->execute(); 
            return [];

    }
    public function actionSetRechargeStatusD(){
        $id = $this->get('id');
        Yii::$app->db->createCommand()->update('user_card_recharge', ['recharge_type' => 4], 'id = :id',['id' => $id])->execute(); 
            return [];

    }

    public function UrlPost($url,$data_string){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)));
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }
    function curl_post($url,$data_string){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }

    public function getUrl($url){
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        //$data = curl_exec($curl);
        $response = curl_exec($curl);

        if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200') {
            list($header, $body) = explode("\r\n\r\n", $response, 2);
        }
        //关闭URL请求
        curl_close($curl);
        //return json_decode($data,TRUE);
        return $body;
    }

    public function actionBeforeRefund(){
        $recharge = UserCardRecharge::findOne(['id'=>$this->get('id')]);
        $this->layout = false; //不使用布局
        $this->layout = "new";
        return $this->render('before_refund',[
            'recharge' => $recharge,
        ]);
    }
    public function actionRefundTest(){
        $id = $this->get('money');
        
        return ['code'=>'0','msg'=>$id];
    }
    
    //执行退款
    public function actionSetRechargeRefund(){
        $id = $this->get('id');
        $trade_type = $this->get('trade_type');
        $source = $this->get('source');
        $reson = $this->get('value');
        $money = $this->get('money');
        $recharge = UserCardRecharge::find()->where(['id'=>$id])->one();
        $reserve = UserCardReserveRecharge::find()->where(['card_recharge_id'=>$recharge->id]);
        $package = Package::findOne(['id'=>$recharge->package_id]);
        $data['id'] = $id;
        $data['card_id'] = $recharge->card_id;
        $data['package_id'] = $recharge->package_id;
        $data['out_trade_no'] = $recharge->trade_no;
        $data['total_fee'] = $recharge->money;
        $data['refund_fee'] = $money;
        $data['source'] = $source;
        $data['refund_reson'] = $reson;
        //根据退款金额大小判断退款状态
        if($money == $recharge->money){
            $refund_status = '5';
        }elseif($money < $recharge->money){
            $refund_status = '6';
        }
        if($trade_type == 3){
            $recharge->recharge_type = 5;
            $recharge->save();
            $profit = AgentProfit::deleteAll(['user_card_recharge_id'=>$recharge->id]);
            if(!empty($reserve)){
                $result = UserCardReserveRecharge::deleteAll(['card_recharge_id'=>$recharge->id]);
            }
            //更改代理商资金
            $account = AgentAccount::findOne(['agent_id'=>$recharge->agent_id]);
            $account_money = $account->money + $recharge->price;
            $account->money = $account_money;
            $account->save();

            $iccid = Card::findOne(['id'=>$recharge->card_id]);
            //生成资金变动记录
            $moneychange = new MoneyChange();
            $moneychange->money_change = $recharge->price;;
            $moneychange->left_money = $account_money;
            $moneychange->recharge_number = $iccid->iccid;
            $moneychange->order_no = "TK".date('Ymd').time();
            $moneychange->create_time = time();
            $moneychange->money_source = 5;
            $moneychange->agent_id = $recharge->agent_id;
            $moneychange->save();
            return [];
        }elseif($trade_type == 1){
            if($source == 3){
                $url = "http://wx.mangcaoiot.com/index.php?g=Wap&m=CiotCard&a=refund";
            }elseif($source == 5){
                $url = "http://wx.mangcaoiot.com/index.php?g=Wap&m=CiotCard&a=refundMangcao";
            }
            $results = $this->curl_post($url,$data);
            $pay_code = json_decode($results,true);
            if($pay_code['code'] == 1){
                //删除代理商收益记录
                $profit = AgentProfit::deleteAll(['user_card_recharge_id' => $id]);
                $card = Card::find()->where(['id'=>$recharge->card_id])->one();
                //预订购退款
                if($recharge->recharge_type == '3'){
                    $result = UserCardReserveRecharge::deleteAll(['card_recharge_id'=>$recharge->id]);
                }else{
                    if(!empty($reserve)){
                        $result = UserCardReserveRecharge::deleteAll(['card_recharge_id'=>$recharge->id]);
                    }
                    //非预订购退款
                    if($package->length_unit == '99'){
                        $flow = $card->total_flow - $package->data;
                        $card->updateAttributes(['total_flow'=>$flow]);
                    }else{
                        $log = CardDatalog::deleteAll(['order_sn'=>$card->order_sn]);
                        $dgcount = $card->dgcs - 1;
                        $card->updateAttributes(
                            ['package_id'=>'','active_time' => '','term_length'=>'','data'=>0,'total_flow'=>'','term_end_time'=>0,'term_length_unit'=>'','order_sn'=>'','dgcs'=>$dgcount,'status' => Card::STATUS_DEACTIVATED ,'order_time'=>'', 'open_id'=>''
                            ]
                        );
                        $active_card = $card->setExecute($card->iccid,5);
                    }
                }
                ManagerLog::info($this->manager->id, '退款', print_r($recharge->attributes, true));
                //最后更改充值状态
                $recharge->recharge_type = $refund_status;
                $recharge->save();
                return ['code' => '200','msg'=>'成功退款'.$money.'元'];
            }else{
                return ['code' => '1001','msg' => $pay_code['msg']];
            }
        }   
    }
    //退款列表
    public function actionRefundList(){
        if(!$this->manager->can('finance/refund-list')){
            throw new ForbiddenHttpException('没有权限');
        }
        $current_time = $this->get('search_time');
        $query = Refund::find()->alias('refund');
        $query->joinWith('card card');
        if(!$current_time){
            $query->andFilterWhere(['refund_time'=> '']);
        }else{
           $query->andFilterWhere(['refund_time' => strtotime($this->get('search_time'))]); 
        } 
        $query->andFilterWhere(['like','card.iccid', $this->get('search_iccid')]);
        $query->andFilterWhere(['refund.out_trade_no' => $this->get('search_trade_no')]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('refund.id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $refundList = $query->all();
        return $this->render('refund_list',[
            'refundList' => $refundList,
            'pagination' => $pagination,
            'current_time' => $current_time
        ]);
    }
    //按日期生成账单
    public function actionMultiCommission(){
        $search_start_time = $this->get('search_start_time');
        $search_end_time = $this->get('search_end_time');
        $start_time = strtotime($this->get('search_start_time'));
        $end_time = strtotime($this->get('search_end_time'));
        
        $query = MultiCommissionBill::find()->alias('bill');
        $query->andFilterWhere(['agentname'=> $this->get('search_username')]);
        
        if(!$search_start_time && !$search_end_time){
            $query->andFilterWhere(['start_time'=>'']);
            $query->andFilterWhere(['end_time'=>'']);
        }else{
            $query->andFilterWhere(['start_time'=>$start_time]);
            $query->andFilterWhere(['end_time'=>$end_time]);
        }
        
        $query->andFilterWhere(['pay_status'=>$this->get('search_status')]);
        $query->andFilterWhere(['bill.id'=>$this->get('search_id')]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy(['id'=>SORT_DESC]);
        $query->offset($pagination->offset)->limit($pagination->limit);
        $billList = $query->all();
        $pay_type = '2';
        $payment_type = '1';  //付款方式：批量付款1,单个付款2
        return $this->render('multi_com_list',[
            'billList' => $billList,
            'pagination' => $pagination,
            'pay_type' => $pay_type,
            'payment_type' => $payment_type
        ]);
    }
    //生成佣金账单账单
    public function actionGenerateMultiAgentBill(){
        $start_time = strtotime($this->get('start'));
        $end_time = strtotime($this->get('end'));
        $agent_name = $this->get('name');
        $agent = Agent::findOne(['username'=>$agent_name]);
        if(empty($agent_name)){
            $agent_id = '';
        }else{
            $agent_id = $agent->id; 
        }
        $profitList = (new \yii\db\Query())
        ->select(['commission_bill.id as id','agent.id as agent_id','agent.username as username','sum(commission_bill.money) as sum_money','commission_bill.create_time as create_time','sum(commission_bill.pay_status) as sum_count'])
        ->from('commission_bill')
        ->join('join','agent','commission_bill.agent_id=agent.id')
        ->groupBy('commission_bill.agent_id')
        ->andFilterWhere(['between','commission_bill.generate_time',$start_time,$end_time])
        ->andFilterWhere(['commission_bill.agent_id'=>$agent_id])
        ->andFilterWhere(['commission_bill.pay_status' => 1])
        ->all();

        // if(!$profitList){
        //     return ['error' => 'EMPTY', 'message' => '所选日期无佣金记录，生成账单失败！'];
        // }
        foreach($profitList as $key=>$value){
            $bill = new MultiCommissionBill();
            $bill->agent_id = $profitList[$key]['agent_id'];
            $bill->start_time = $start_time;
            $bill->end_time = $end_time;
            $bill->money = $profitList[$key]['sum_money'];
            $bill->create_time = time();
            $bill->agentname = $profitList[$key]['username'];
            $bill->count = $profitList[$key]['sum_count'];
            $bill->save();
        }
        return [];   
    }
    /**
     * 流量分段统计详情
     */
    public function actionSubView(){
        $id = $this->get('id');
        $card = Card::findOne(['id'=>$id]);
        $query = CardUsageSub::find()->alias('sub');
        $query->joinWith('card card');
        $query->joinWith('agent agent');
        $query->joinWith('package package');
        $query->andFilterWhere(['card_id'=>$id]);
        $query->orderBy('sub.id asc');
        $subList = $query->all();
        $this->layout = false; //不使用布局
        $this->layout = "new";
        return $this->render('sub_view',[
            'subList' => $subList,
            'card' => $card
        ]);
    }
    /**
     * 修改账单金额AJAX接口
     * @return array
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionModifyCommissionMoney()
    {
        $bill = CommissionBill::findOne(['id' => $this->get('id')]);
        if (empty($bill)) {
            throw new NotFoundHttpException('没有找到账单。');
        }
        $bill->money = $this->get('money');
        $bill->save();
        ManagerLog::info($this->manager->id, '修改佣金账单金额', print_r($this->get(), true));

        return [];
    }
    /**
     * 删除代理商收益并更改账单金额
     */
    public function actionDeleteProfit(){
        $id = $this->get('id');
        $profit = AgentProfit::findOne(['id'=>$id]);
        $bill = CommissionBill::findOne(['generate_time'=>$profit->same_time,'agent_id'=>$profit->agent_id]);
        $money = $bill->money - $profit->money;
        $bill->money = $money;
        $bill->save();
        $list = AgentProfit::deleteAll(['id'=>$id]);
        return [];
        
    }
    /**
     * 删除卡充值列表
     */
    public function actionDeleteRecharge(){
        $id = $this->get('id');
        $profit = AgentProfit::deleteAll(['user_card_recharge_id'=>$id]);
        $recharge = UserCardRecharge::deleteAll(['id'=>$id]);
        return [];
    }

    /**
     * 重新生成卡周期流量记录
     */
    public function actionReGenerateUsage(){
        $id = $this->get('id');
        $sub = CardUsageSub::find()->where(['card_id'=>$id])->all();
        $card = Card::findOne(['id'=>$id]);
        $time = (29*86400);
        //先删除表中已经存在的记录
        $usage = CardUsageSub::deleteAll(['card_id'=>$id]);
        //循环查询出card_datalog表中的记录
        for ($i=1; $i <3 ; $i++) { 
            $profitList = (new \yii\db\Query())
            ->select(['card_datalog.id','card_datalog.card_id','card_datalog.order_sn','card_datalog.startdate','sum(card_datalog.data) as sum_data'])
            ->from('card_datalog')
            ->groupBy('card_datalog.order_sn')
            ->andFilterWhere(['card_datalog.card_id'=>$id])
            ->offset($i)
            ->limit(1)
            ->orderBy('id desc')
            ->all();
            //再取出需要的记录
            $recharge = UserCardRecharge::findOne(['create_time'=>$profitList[0]['startdate']]);
            //查询套餐虚值
            $xuzhi = AgentPackage::findOne(['agent_id'=>$card->agent_id,'package_id'=>$recharge->package_id]);
            //判断虚值是否为空，然后赋值
            if(empty($xuzhi)){
                $fakeNumber = 0.75;
            }else{
                $fakeNumber = $xuzhi->xuzhi;
            }
            //计算用量并写入表中
            foreach ($profitList as $key => $value) {
                $sub = new CardUsageSub();
                $sub->agent_id = $card->agent_id;
                $sub->card_id = $value['card_id'];
                $sub->package_id = $recharge->package_id;
                $sub->start_date = $value['startdate'];
                $end_date = $value['startdate'] + $time;
                $sub->end_date = strtotime(date('Y-m-d',$end_date))+86399;
                $sub->data_isp = $value['sum_data'];
                $sub->data = $value['sum_data'] /$fakeNumber ;
                $sub->create_time = time();
                $sub->save(); 
            }    
        }
        //返回结果
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ['code'=>'1','msg'=>'生成成功'];
    }

}
